package com.jvtd.eyl.ui.login;

import com.jvtd.eyl.base.BasePresenter;
import com.jvtd.eyl.bean.db.User;
import com.jvtd.eyl.bean.http.LoginReqBean;
import com.jvtd.eyl.bean.http.LoginResBean;
import com.jvtd.eyl.bean.http.LoginUserBean;
import com.jvtd.eyl.data.DbManager;
import com.jvtd.eyl.rxjava.JvtdRxSchedulers;
import com.jvtd.rxjava.JvtdObserverSubscriber;

import javax.inject.Inject;

import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;

/**
 * 登录
 * <p>
 * 作者:chenlei
 * 时间:2018/11/12 3:21 PM
 */
public class LoginPresenter<V extends LoginMvpView> extends BasePresenter<V>
        implements LoginMvpPresenter<V> {

    @Inject
    public LoginPresenter(DbManager dbManager, CompositeDisposable disposable) {
        super(dbManager, disposable);
    }

    @Override
    public void loginAccount(String token) {
        if (!isAttachView()) return;
        LoginReqBean loginReqBean = new LoginReqBean();
        LoginReqBean.TokenBean tokenBean = new LoginReqBean.TokenBean();
        tokenBean.setToken(token);
        loginReqBean.setData(tokenBean);
        getCompositeDisposable().add(getDbManager().login(loginReqBean).compose(JvtdRxSchedulers
                .handleOtherObservableResult()).subscribeWith(new JvtdObserverSubscriber<LoginResBean>(getMvpView()) {
            @Override
            public void onNext(@NonNull LoginResBean loginResBean) {
                super.onNext(loginResBean);
                if (LoginResBean.LOGIN_SUCCESS_CODE.equals(loginResBean.getStatus())) {
                    validationUser(loginResBean.getData(), token);
                } else
                    getMvpView().loginFailed(loginResBean.getMsg());
            }

            @Override
            public void onError(@NonNull Throwable e) {
                super.onError(e);
            }
        }));
    }

    /**
     * 验证用户
     *
     * @param userBean 用户信息实体
     * @param token    token
     */
    public void validationUser(LoginUserBean userBean, String token) {
        if (!isAttachView()) {
            getMvpView().loginFailed(null);
            return;
        }
        User user = new User();
        user.setUserId(userBean.getEmployeenum());
        user.setName(userBean.getName());
        user.setDepartment(userBean.getDepartment());
        saveUserInfo(user);
    }

    /**
     * 保存用户
     *
     * @param user 用户数据库实体
     */
    private void saveUserInfo(final User user) {
        // 保存当前用户信息到数据库
        User.deleteAll(User.class);
        getCompositeDisposable().add(getDbManager().saveCurrentUser(user).map(isSuccess -> isSuccess)
                .subscribe(isSuccess -> {
                    if (isSuccess && isAttachView()) {
//        getDbManager().setLogin();

                        getMvpView().loginSuccess();
                    }
                }));
    }
}
